package com.lzxr.test.servlet;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

public class DownServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取文件的路径
        String filePath = request.getParameter("fileName");

        String currentPath = System.getProperty("user.dir");
        File file = new File(currentPath+"/files/download/"+filePath);

        // 得到input stream
        FileInputStream in = new FileInputStream(file);

        // 设置响应头
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment; filename=" + file.getName());
        OutputStream out = response.getOutputStream();
        byte[] bu = new byte[1024 * 4];
        int len = 0;
        while ((len = in.read(bu)) != -1) {
            out.write(bu, 0, len);
        }

        //关闭资源
        in.close();
        out.close();
    }
}
